import { core_view } from "../view/core_view";
import { core_viewmodel } from "./core_viewmodel";

class ViewModelManager {
    private static _instance: ViewModelManager;
    private readonly viewModelMap: WeakMap<core_view, core_viewmodel> = new WeakMap();
    
    private constructor() {
        // 私有构造函数，确保单例模式
    }
    
    public static getInstance(): ViewModelManager {
        if (!ViewModelManager._instance) {
            ViewModelManager._instance = new ViewModelManager();
        }
        return ViewModelManager._instance;
    }


    /**
     * 添加ViewModel到映射中
     * @param view 视图实例
     * @param viewModel ViewModel实例
     */
    public addViewModel(view: core_view, viewModel: core_viewmodel): void {
        this.viewModelMap.set(view, viewModel);
    }

    /**
     * 获取指定视图的ViewModel
     * @param view 视图实例
     * @returns ViewModel实例，如果不存在则返回null
     */
    public getViewModel(view: core_view): core_viewmodel | null {
        return this.viewModelMap.get(view) || null;
    }

    /**
     * 创建或获取ViewModel实例
     * 如果指定视图已有ViewModel，则返回现有实例；否则创建新实例
     * @param view 视图实例
     * @param viewModelConstructor ViewModel构造函数
     * @returns ViewModel实例
     */
    public createViewModel(view: core_view, viewModelConstructor: new () => core_viewmodel): core_viewmodel {
        if (!view) {
            throw new Error('View实例不能为null或undefined');
        }
        
        if (!viewModelConstructor) {
            throw new Error('ViewModel构造函数不能为null或undefined');
        }
        
        // 先尝试获取已存在的ViewModel
        const existingViewModel = this.getViewModel(view);
        
        if (existingViewModel) {
            return existingViewModel;
        }
        
        // 如果不存在，创建新的ViewModel并添加到映射中
        try {
            const newViewModel = new viewModelConstructor();
            this.addViewModel(view, newViewModel);
            return newViewModel;
        } catch (error) {
            throw new Error(`创建ViewModel失败: ${error instanceof Error ? error.message : '未知错误'}`);
        }
    }

    /**
     * 移除指定视图的ViewModel
     * @param view 视图实例
     * @returns 是否成功移除
     */
    public removeViewModel(view: core_view): boolean {
        if (!view) {
            return false;
        }
        
        const hasViewModel = this.viewModelMap.has(view);
        if (hasViewModel) {
            this.viewModelMap.delete(view);
        }
        return hasViewModel;
    }

    /**
     * 检查指定视图是否有ViewModel
     * @param view 视图实例
     * @returns 是否存在ViewModel
     */
    public hasViewModel(view: core_view): boolean {
        return view ? this.viewModelMap.has(view) : false;
    }
}

export const vmManager = ViewModelManager.getInstance();